﻿using System;
using System.Collections.Generic;
using System.Linq;

using Facebook.Rest;
using Facebook.Schema;
using Facebook.Utility;

using SBPweb.RIA.Client.Controls.Base;

using SBPweb.PlAzureNet.Client.Library.Social.Friends;

namespace SBPweb.PlAzureNet.Client.Modules.Facebook.API.Friends
{

    public class FriendManager : FriendManagerBase
    {

        #region Fields

        private Api api;
        private int batchCount = 20;

        #endregion

        #region Constructor logic

        internal FriendManager(Api api)
        {
            this.api = api;
        }

        #endregion

        #region Methods

        public override void FetchFriends()
        {
            OnFetching();

            api.Friends.GetAsync(new global::Facebook.Rest.Friends.GetFriendsCallback(friends_GetFriendsCompleted), null);
        }

        #endregion

        #region Event handlers

        private void friends_GetFriendsCompleted(IList<long> uids, Object state, FacebookException e)
        {
            if (e != null)
            {
                throw e;
            }
            EstimatedFriendCount = uids.Count;

            for (int i = 0; i < EstimatedFriendCount; i += batchCount)
            {
                api.Users.GetInfoAsync(uids.Skip(i).Take(batchCount).ToList(), new Users.GetInfoCallback(GetUserInfoCompleted), null);
            }
        }

        private void GetUserInfoCompleted(IList<user> users, Object state, FacebookException e)
        {
            if (e != null)
            {
                throw e;
            }
            Connector.Instance.Dispatcher.BeginInvoke(() =>
            {
                foreach (var u in users)
                {
                    Add(new User(u));
                }
                this.Sort();
                if (Count >= EstimatedFriendCount)
                {
                    OnFetched();
                }
            });
        }

        #endregion

    }

}